//
//  XCAVMusicPlayer.m
//  TTLestening
//
//  Created by dllo on 16/3/25.
//  Copyright © 2016年 dilo. All rights reserved.
//

#import "XCAVMusicPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import "XCModelForEveryone.h"
#import "ZFPlayer.h"

@interface XCAVMusicPlayer ()
@property (nonatomic) NSTimer *timer;
@property (nonatomic, strong)AVPlayer *player;
@property (nonatomic, strong)AVPlayerItem *playItem;
@property (nonatomic, assign) CGFloat totalMovieDuration; // 保存该视频资源的总时长，快进或快退的时候要用
@property (nonatomic, strong)NSMutableArray *array;
@property (nonatomic, assign)NSInteger index;

@end

@implementation XCAVMusicPlayer

+(instancetype)sharedMusicPlayer {
 
    static XCAVMusicPlayer *music = nil;
    static dispatch_once_t predicate;
    
    dispatch_once(&predicate, ^{
       
        music = [[XCAVMusicPlayer alloc] init];
        
    });
    
    return music;

}

- (instancetype)init {

    self = [super init];
    
    if (self) {
        
        self.player = [AVPlayer playerWithPlayerItem:self.playItem];
    
        [[NSNotificationCenter defaultCenter] addObserverForName:@"1314" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
           
           // [self passMusicUrl:[note.userInfo objectForKey:@"music"]];
            [self passMusicUrl:[note.userInfo objectForKey:@"music"] index:[[note.userInfo objectForKey:@"index"] integerValue]];
            
            self.array = [note.userInfo objectForKey:@"music"];
            self.index = [[note.userInfo objectForKey:@"index"] integerValue];

            
            
        }];
        
        
        [[NSNotificationCenter defaultCenter] addObserverForName:@"pause" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
           
            [self.player pause];
            
        }];
        
        [[NSNotificationCenter defaultCenter] addObserverForName:@"play" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
           
            [self.player play];
            
        }];
        
        
        [[NSNotificationCenter defaultCenter] addObserverForName:@"nextSong" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
           
           // NSLog(@"%@", [note.userInfo objectForKey:@"index"]);
            
            NSArray *array = [note.userInfo objectForKey:@"array"];
            NSInteger index = [[note.userInfo objectForKey:@"index"] integerValue];
            
            if (index > array.count - 1) {
                
                NSLog(@"歌单播放完毕");
                
              //  return;
                
            }else {

            
          //  NSInteger nexSong = ++index;
           // NSLog(@"%ld", nexSong);
            
                [self passMusicUrl:array index:index];
            }
            
            
            
        }];
        
        
        
        [[NSNotificationCenter defaultCenter] addObserverForName:@"lastSong" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
            
         //   NSLog(@"%@", [note.userInfo objectForKey:@"index"]);
            
            NSArray *array = [note.userInfo objectForKey:@"array"];
            NSInteger index = [[note.userInfo objectForKey:@"index"] integerValue];
            
            if (index < 0) {
                
                NSLog(@"歌单播放完毕");
                
                //  return;
                
            }else {
                
                
                //  NSInteger nexSong = ++index;
                // NSLog(@"%ld", nexSong);
                
                [self passMusicUrl:array index:index];
            }
            
            
            
        }];
        
        
        
        [self addNotificationEnd];
        
    }
    
    return self;
}



- (void)passMusicUrl:(NSArray *)songArr index:(NSInteger)index{

    
    
    XCModelForEveryone *model = [songArr objectAtIndex:index];
    
    NSString *url = [[model.urlList lastObject] objectForKey:@"url"];
   
    
    url =[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  
    
    NSURL *urld=[NSURL URLWithString:url];
    
    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"history.plist"];

    
    NSDictionary *dicForDictory = @{@"name":model.name,
                                    @"picUrl":model.picUrl,
                                    @"urld":url};

    
     [dicForDictory writeToFile:file atomically:YES];
    
    self.playItem = [[AVPlayerItem alloc] initWithURL:urld];
    [self.player replaceCurrentItemWithPlayerItem:self.playItem];
    
    __block XCAVMusicPlayer *vc = self;
    
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 30) queue: dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        
        vc.duration = CMTimeGetSeconds(vc.playItem.duration);
        //当前时间
        vc.current = CMTimeGetSeconds(vc.player.currentTime);
        vc.progress = vc.current / vc.duration;
        
        NSString *duration = [NSString stringWithFormat:@"%f",vc.duration];
        NSString *current = [NSString stringWithFormat:@"%f",vc.current];
        NSString *progress = [NSString stringWithFormat:@"%f",vc.progress];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"pushprogress" object:nil userInfo:@{@"duration":duration, @"current" :current , @"progress" :progress}];
        
    }];
    
    
    [self.player play];
    
}

- (void)setVideoURL:(NSURL *)videoURL {
    
   // NSLog(@"%@", videoURL);
    self.playItem = [[AVPlayerItem alloc] initWithURL:videoURL];
    [self.player replaceCurrentItemWithPlayerItem:self.playItem];
    
    __block XCAVMusicPlayer *vc = self;
    
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 30) queue: dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        
        vc.duration = CMTimeGetSeconds(vc.playItem.duration);
        //当前时间
        vc.current = CMTimeGetSeconds(vc.player.currentTime);
        vc.progress = vc.current / vc.duration;
        
        NSString *duration = [NSString stringWithFormat:@"%f",vc.duration];
        NSString *current = [NSString stringWithFormat:@"%f",vc.current];
        NSString *progress = [NSString stringWithFormat:@"%f",vc.progress];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"pushprogress" object:nil userInfo:@{@"duration":duration, @"current" :current , @"progress" :progress}];
        
    }];
    
    
    [self.player play];
    
}



/** 添加播放完毕的观察者 */
- (void)addNotificationEnd {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

- (void)playEnd:(NSNotification *) end {
    
    NSLog(@"播放完毕");
    
    ++self.index;
    
    if (self.index >self.array.count - 1) {
        
        NSLog(@"歌单播放完毕");
        return;
        
    }else {
    
        NSLog(@"自动换歌");
        
    [self passMusicUrl:self.array index:self.index];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"giveValue" object:nil userInfo:@{@"modelArray": self.array, @"index": [NSString stringWithFormat:@"%ld",self.index]}];
    }
    
}






@end
